<script setup lang="ts">
import { useMemberStore } from '@/stores'
import {
  GetDetailDataAPI,
  GetUserSettingAPI,
  UpdateUserSettingAPI,
  type GetDetailDataParams,
  GetGoodDetailAPI,
  DelGoodAPI,
  GetUserAccountAPI,
  ShowYuSuanAPI,
  UpdateGoodAPI,
  GetNoticeAPI,
  CloseNoticeAPI,
  GetAccountTypeNameAPI,
  AppleAddAPI,
  GetGroupAPI,
} from '@/services/detail'
import { onLoad, onShow, onTabItemTap } from '@dcloudio/uni-app'
import type {
  AccountDetail,
  AccountTypeNameResponse,
  DataCount,
  ShowYuSuanResponse,
  UserAccount,
  UserSetting,
} from '@/types/detail'
import { ref, computed } from 'vue'
import { GetVersionAPI, SearchFileOneAPI } from '@/services/img'
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
//变量
const shouruAmount = ref(0.0)
const zhichuAmount = ref(0.0)
const form = ref<GetDetailDataParams>({
  UserName: '',
  DealYear: 2024,
  DealMonth: 7,
  AccountNo: '',
  Auth: '',
  DealDay: 0,
  GoodsType: '',
  Goods: '',
  InOut: 0,
  TimeScope: '',
  OrderBy: 1,
  Require: '',
  UserGroup: '',
  LoginName: '',
})
const backgroundImgMain = ref('')
const opacity = ref(0.7)
const noticeMsg = ref<string>()
const userSetting = ref<UserSetting>()
const showMask = ref(false)
const data = ref<DataCount[]>()
const goodDetail = ref<AccountDetail>({
  ID: 0,
  AccountNo: '',
  UserName: '',
  DealTime: new Date(),
  DuiFang: '',
  Goods: '',
  InOut: 0,
  Amount: 0,
  Remark: '',
  GoodsType: '',
  Source: '',
  GoodsIcon: '',
  AccountName: '',
  AccountTypeName: '',
  AccountCard: '',
  IsNotYuSuan: false,
  IsAvg: false,
  IsRequire: false,
  IsNotMonthAccount: true,
})
const version = ref('')
const yusuan = ref<ShowYuSuanResponse>()
//计算属性
const maskedshouruAmount = computed(() => {
  if (showMask.value) {
    const amountStr = shouruAmount.value.toString()
    const maskedStr = '*'.repeat(amountStr.length)
    return maskedStr
  } else {
    return shouruAmount.value
  }
})
const maskedzhichuAmount = computed(() => {
  if (showMask.value) {
    const amountStr = zhichuAmount.value.toString()
    const maskedStr = '*'.repeat(amountStr.length)
    return maskedStr
  } else {
    return zhichuAmount.value
  }
})
// 用户信息
const memberStore = useMemberStore()
const userAccounts = ref<UserAccount[]>()
const accountTypeNames = ref<AccountTypeNameResponse[]>()
const curUserAccount = ref<UserAccount>()
const curAccountTypeName = ref<AccountTypeNameResponse>({
  AccountTypeName: 'ALL',
})
const chartsDataArcbar1 = ref({
  series: [
    {
      data: 0,
      color: '#fdc3bc',
    },
  ],
})
onShow(async () => {
  // const res1 = await GetVersionAPI({
  //   Auth: '',
  // })
  // if (version.value != res1.result.Version) {
  //   window.location.reload()
  // }
  await InitNotice()
  await reFresh()
  //个性主题
  if (memberStore.profile) {
    const detail = await SearchFileOneAPI({
      ImgType: 'detail',
      UserName: memberStore.profile.UserName,
      ID: 0,
    })
    if (detail.result) {
      backgroundImgMain.value = detail.result.ImgUrl
    }
    const setting = await GetUserSettingAPI({
      UserName: memberStore.profile.UserName,
    })
    opacity.value = setting.result.DetailOpacit / 10
  }
})
//初始化
onLoad(async () => {
  if (memberStore.profile) {
    await UpdateCookie()
    form.value.Auth = memberStore.profile!.Token
    form.value.UserGroup = memberStore.profile!.UserGroup
    form.value.LoginName = memberStore.profile!.UserName
    const res1 = await GetVersionAPI({
      Auth: '',
      UserGroup: '',
    })
    version.value = res1.result.Version
    var now = new Date()
    if (now.getMonth() == 6 && now.getDate() == 23) {
      uni.reLaunch({
        url: '/pages/plan/Cake',
      })
    }
    await InitUserSetting()
    showMask.value = userSetting.value?.IsAmount!
    //初始化用户账号
    await InitAccountNo()
    //初始化账户
    await InitUserAccount()
    //初始化账户类别
    await InitAccountTypeName()
    //获取当前账户
    GetUserAccount(form.value.AccountNo)
    //初始化预算
    await InitYuSuan()
    //初始化通知
    await InitNotice()
    //初始化年月
    const currentDate = new Date()
    form.value.DealYear = currentDate.getFullYear()
    form.value.DealMonth = currentDate.getMonth() + 1

    reFresh()
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
})
//更新cookie
const UpdateCookie = async () => {
  if (memberStore.profile) {
    const res = await GetGroupAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
    })
    memberStore.setProfile(res.result)
  }
}
//金额隐藏事件
const toggleMask = () => {
  userSetting.value!.IsAmount = !showMask.value
  showMask.value = !showMask.value
  UpdateUserSetting()
}
//刷新事件
const reFresh = async () => {
  if (memberStore.profile) {
    if (form.value.Auth) {
      const res = await GetDetailDataAPI(form.value)
      data.value = res.result
      shouruAmount.value = res.result[0]?.ShouruAmount | 0
      zhichuAmount.value = res.result[0]?.ZhichuAmount | 0
      uni.showToast({ icon: 'success', title: '刷新成功' })
    }
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
//查询自己
const searchself = async () => {
  if (userSetting.value!.IsSearchSelf) {
    form.value.UserName = ''
    userSetting.value!.IsSearchSelf = !userSetting.value!.IsSearchSelf
  } else {
    form.value.UserName = memberStore.profile!.UserName
    userSetting.value!.IsSearchSelf = !userSetting.value!.IsSearchSelf
  }
  UpdateUserSetting()
  reFresh()
}
//日期改变
const bindDateChange = (e: any) => {
  const [year, month] = e.detail.value.split('-')
  form.value.DealYear = year
  form.value.DealMonth = month
  reFresh()
}
//初始化用户配置
const InitUserSetting = async () => {
  if (memberStore.profile) {
    const res = await GetUserSettingAPI({ UserName: memberStore.profile.UserName })
    userSetting.value = res.result
  }
}

//修改用户配置
const UpdateUserSetting = async () => {
  if (memberStore.profile) {
    await UpdateUserSettingAPI(userSetting.value!)
  }
}
//初始化用户配置
const InitAccountNo = async () => {
  if (memberStore.profile) {
    const res = await GetUserSettingAPI({ UserName: memberStore.profile.UserName })
    form.value.AccountNo = res.result.DefaultAccountNo
    curAccountTypeName.value.AccountTypeName = res.result.DefaultAccountNo
  }
}
//初始化账户列表
const InitUserAccount = async () => {
  if (memberStore.profile) {
    const res = await GetUserAccountAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountNo: '',
      UserName: '',
      AccountTypeName: 'ALL',
      AccountCard: 'ALL',
      Display: 'ALL',
      Remark: '',
    })
    userAccounts.value = res.result
  }
}
//初始化账户类型列表
const InitAccountTypeName = async () => {
  if (memberStore.profile) {
    const res = await GetAccountTypeNameAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountTypeName: 'ALL',
    })
    accountTypeNames.value = res.result
  }
}

//初始化预算
const InitYuSuan = async () => {
  if (memberStore.profile) {
    const res = await ShowYuSuanAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    yusuan.value = res.result
    chartsDataArcbar1.value.series[0].data = res.result.UseAmountScale
  }
}
//初始化通知
const InitNotice = async () => {
  if (memberStore.profile) {
    const res = await GetNoticeAPI({
      Auth: memberStore.profile.Token,
      UserName: memberStore.profile.UserName,
      UserGroup: memberStore.profile.UserGroup,
    })
    noticeMsg.value = res.result.NoticeMsg
  }
}
//获取用户账户名
const GetUserAccount = (accountNo: string) => {
  if (memberStore.profile) {
    curUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == accountNo)
  }
}
//弹出层
// uni-ui 弹出层组件
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const openPopup = async (id: number) => {
  popup.value?.open()
  const res = await GetGoodDetailAPI({ ID: id })
  goodDetail.value = res.result
}

//提示框
const alertDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const OnAlertDialog = async () => {
  alertDialog.value?.open()
}
//修改商品
const OnUpdateGood = async () => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url:
      '/pages/NoteAcount/NoteAcount?pageType=update&id=' +
      goodDetail.value!.ID +
      '&backPage=/pages/Detail/Detail',
  })
}
//拷贝商品
const OnCopy = async () => {
  const res = await AppleAddAPI({
    UserName: memberStore.profile!.UserName,
    InOut: goodDetail.value.InOut == 1 ? '收入' : '支出',
    GoodsType: goodDetail.value.GoodsType,
    Goods: goodDetail.value.Goods,
    Amount: goodDetail.value.Amount,
    DealTimeStr: '',
    Auth: memberStore.profile!.Token,
    Source: '拷贝',
    AccountNo: goodDetail.value.AccountNo,
    OutAccountNo: '',
    InAccountNo: '',
    IsNotYuSuan: goodDetail.value.IsNotYuSuan,
    IsAvg: goodDetail.value.IsAvg,
    IsRequire: goodDetail.value.IsRequire,
    UserGroup: memberStore.profile!.UserGroup,
    IsNotMonthAccount: goodDetail.value.IsNotMonthAccount,
  })
  popup.value?.close()
  reFresh()
}
//确认删除
const delGood = async () => {
  await DelGoodAPI({
    ID: goodDetail.value!.ID,
    Auth: memberStore.profile!.Token,
  })
  alertDialog.value?.close()
  popup.value?.close()
  reFresh()
}
//取消
const cancel = async () => {
  alertDialog.value?.close()
}
const orderby = async () => {
  form.value.OrderBy = form.value.OrderBy == 1 ? 2 : 1
  await reFresh()
}
//选择账户
const pickerAccountChange = (e: any) => {
  const index = e.detail.value as number
  curUserAccount.value = userAccounts.value![index]
  form.value.AccountNo = curUserAccount.value.AccountNo
  reFresh()
}
//修改商品-选择修改账户
const pickerInAccountChange = (e: any) => {
  const index = e.detail.value as number
  var curUserAccount = userAccounts.value![index]
  goodDetail.value!.AccountNo = curUserAccount.AccountNo
  goodDetail.value!.AccountName = curUserAccount.UserName
  goodDetail.value!.AccountTypeName = curUserAccount.AccountTypeName
  goodDetail.value!.AccountCard = curUserAccount.AccountCard
}
// 是否触发下拉刷新
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 加载数据
  await reFresh()
  // 关闭动画
  isTriggered.value = false
}
//===查询弹窗===
const searchDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
//打开
const OpenSarchDialog = async () => {
  searchDialog.value?.open()
}
//确认
const SubmitSarchDialog = async () => {
  reFresh()
  CloseSarchDialog()
}
//取消
const CloseSarchDialog = async () => {
  searchDialog.value?.close()
}
//选择账户
const pickerSearchAccountChange = (e: any) => {
  const index = e.detail.value as number
  curUserAccount.value = userAccounts.value![index]
  form.value.AccountNo = curUserAccount.value.AccountNo
}
//选择账户类型
const pickerAccountTypeChange = (e: any) => {
  const index = e.detail.value as number
  curAccountTypeName.value = accountTypeNames.value![index]
  form.value.AccountNo = curAccountTypeName.value.AccountTypeName
  reFresh()
}
//关闭通知
const closeNotice = async (p0: {}) => {
  if (memberStore.profile) {
    await CloseNoticeAPI({
      Auth: memberStore.profile.Token,
      UserName: memberStore.profile.UserName,
      UserGroup: memberStore.profile.UserGroup,
    })
  }
}
const onIsNotYuSuan = (e: any) => {
  goodDetail.value.IsNotYuSuan = e.detail.value[0] || false
}
</script>
<template>
  <uni-notice-bar
    v-if="noticeMsg"
    show-icon
    show-close
    :text="noticeMsg"
    speed="80"
    @close="closeNotice"
  />
  <scroll-view
    enable-back-to-top
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
  >
    <view class="viewport">
      <view
        class="viewport1"
        :style="`background: url('${backgroundImgMain}')  no-repeat center / cover;opacity: ${opacity}`"
      ></view>
      <!-- header -->
      <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
        <view class="header1">
          <navigator
            v-if="userSetting?.SoftStyle != '简约'"
            class="zushou icon-zushou"
            url="/pages/Detail/Smart"
            hover-class="none"
          ></navigator>
          <view
            class="searchself icon-searchself"
            :class="{ Active: userSetting?.IsSearchSelf }"
            @tap="searchself"
          >
            <text class="onlyMe"></text>
          </view>
          <view class="title"><text @tap="reFresh">连太记账</text></view>
          <view class="search icon-sort" @tap="orderby()"></view>
          <!-- <view class="search icon-chaxun" @tap="OpenSarchDialog()"></view> -->
          <navigator
            class="rili icon-rili"
            url="/pages/Detail/Calendar"
            hover-class="none"
          ></navigator>
        </view>
        <view class="header2" v-if="userSetting?.SoftStyle != '简约'">
          <view>
            <picker
              mode="date"
              fields="month"
              :value="form.DealYear"
              start="2024-01-01"
              end="2034-12-30"
              @change="bindDateChange"
            >
              <view class="time">
                <text class="txt1">{{ form.DealYear }}年</text>
                <text class="txt2">{{ form.DealMonth }}月</text>
              </view>
            </picker>
          </view>
          <view class="shouru">
            <text class="txt1">总收入</text>
            <text @tap="toggleMask">{{ maskedshouruAmount }}</text>
          </view>
          <view class="zhichu">
            <text class="txt1">总支出</text>
            <text @tap="toggleMask">{{ maskedzhichuAmount }}</text>
          </view>
          <view class="zhichu">
            <text class="txt1">结余</text>
            <text @tap="toggleMask">{{ maskedshouruAmount + maskedzhichuAmount }}</text>
          </view>
          <view>
            <picker
              @change="pickerAccountTypeChange"
              mode="selector"
              :range="accountTypeNames"
              range-key="AccountTypeName"
            >
              <text class="account">{{ curAccountTypeName.AccountTypeName }}</text></picker
            >
          </view>
        </view>
      </view>
      <!-- 预算 -->
      <view
        v-if="userSetting?.SoftStyle != '简约'"
        class="orders"
        :class="{ warn: yusuan && Math.abs(yusuan.UseAmountAvg) > yusuan.NotUseAmountAvg }"
      >
        <view class="title">本月日常支出预算： {{ yusuan?.PlanAmount }}</view>
        <view class="yscontent">
          <view class="left">
            <view class="chart">
              <qiun-data-charts
                type="arcbar"
                :opts="{
                  title: {
                    name: Math.round((yusuan?.UseAmountScale || 0) * 100) + '%',
                    color: '#333',
                    fontSize: 10,
                  },
                  subtitle: { name: '已用', color: '#333', fontSize: 10 },
                  extra: { arcbar: { width: 5 } },
                }"
                :chartData="chartsDataArcbar1"
              />
            </view>
            <view>
              <view class="smallfont">已用 {{ yusuan?.UseAmount }}</view>
              <view class="smallfont gray">已用日均 {{ yusuan?.UseAmountAvg }}</view>
            </view>
          </view>
          <view class="right">
            <text class="smallfont boldfont">可用 {{ yusuan?.NotUseAmount }}</text>
            <text class="smallfont gray">剩余日均 {{ yusuan?.NotUseAmountAvg }}</text>
          </view>
        </view>
      </view>

      <!-- 具体明细 -->
      <!-- <scroll-view enable-back-to-top scroll-y class="scroll"> -->
      <view class="scroll">
        <view class="content">
          <view class="detail" v-for="dataCount in data" :key="dataCount.MonthDay">
            <view class="tip">
              <view>{{ dataCount.MonthDay }} {{ dataCount.Week }}</view>
              <view>收支: {{ dataCount.TotalAmount }}</view>
            </view>
            <view class="content" v-for="data in dataCount.Data" :key="data.ID">
              <view class="name" @tap="openPopup(data.ID)">
                <view
                  v-if="data?.GoodsIcon.startsWith('icon')"
                  class="circle"
                  :class="[
                    data?.GoodsIcon,
                    { circleColorMan: data?.UserName == memberStore.profile?.UserName },
                  ]"
                ></view>
                <view
                  v-else
                  class="circle bold"
                  :class="{ circleColorMan: data?.UserName == memberStore.profile?.UserName }"
                  >{{ data?.GoodsIcon }}</view
                >
                <view>{{ data.Goods }}</view>
                <!-- <uni-tag text="标签" :inverted="true" type="warning" size="small" :circle="true" /> -->
                <view class="userName">{{ data.AccountTypeName }}</view>
              </view>
              <view>{{ data.Amount }}</view>
            </view>
          </view>
        </view>
      </view>
      <!-- </scroll-view> -->
    </view>
    <view>
      <!-- 商品详情 弹窗 -->
      <uni-popup
        ref="popup"
        type="bottom"
        borderRadius="20rpx"
        background-color="#fafafa"
        @close="popup?.close()"
      >
        <view class="popup-content popup">
          <view class="pheader">
            <text class="title">账单详情</text>
            <text
              v-if="goodDetail?.InOut == 1 || goodDetail?.InOut == 2"
              class="btn ok"
              @tap="OnCopy()"
              >拷 贝</text
            >
            <text class="btn ok" @tap="OnUpdateGood()">修 改</text>
            <text class="btn del" @tap="OnAlertDialog()">删 除</text>
          </view>
          <view class="content">
            <view class="Good">
              <view
                v-if="goodDetail?.GoodsIcon.startsWith('icon')"
                class="circle"
                :class="goodDetail?.GoodsIcon"
              ></view>
              <view v-else class="circle bold">{{ goodDetail?.GoodsIcon }}</view>

              <view>{{ goodDetail?.Goods }}</view>
              <view class="userName">({{ goodDetail?.UserName }})</view>
              <view>
                {{ goodDetail.Amount }}
              </view>
            </view>
            <view class="zhichu">
              <text>账号</text>
              <picker
                @change="pickerInAccountChange"
                mode="selector"
                :range="userAccounts"
                range-key="Display"
              >
                <text
                  >{{ goodDetail?.AccountName }}/{{ goodDetail?.AccountTypeName }}/{{
                    goodDetail?.AccountCard
                  }}</text
                ></picker
              >
            </view>
            <view class="zhichu">
              <text>不计入预算</text>
              <checkbox-group @change="onIsNotYuSuan" class="isnotyusuan">
                <label>
                  <checkbox :value="true" :checked="goodDetail?.IsNotYuSuan" />
                </label>
              </checkbox-group>
            </view>
            <view class="zhichu">
              <text>对方</text>
              <text>{{ goodDetail?.DuiFang }}</text>
            </view>
            <view class="zhichu">
              <text>来源</text>
              <text>{{ goodDetail?.Source }}</text>
            </view>
            <view class="zhichu">
              <text>时间</text>
              <text>{{ goodDetail?.DealTime }}</text>
            </view>
            <view class="zhichu">
              <text>备注</text>
              <text>{{ goodDetail?.Remark }}</text>
            </view>
          </view>
        </view>
      </uni-popup>
      <!-- 提示确认是否删除 弹窗 -->
      <uni-popup ref="alertDialog" type="dialog">
        <uni-popup-dialog
          type="warn"
          cancelText="取消"
          confirmText="确定"
          title="通知"
          content="确定要删除么？"
          @confirm="delGood"
          @close="cancel"
        ></uni-popup-dialog>
      </uni-popup>
      <!-- 搜索商品 弹窗 -->
      <uni-popup
        ref="searchDialog"
        borderRadius="20rpx"
        background-color="#fafafa"
        @close="searchDialog?.close()"
      >
        <view class="popup-content popup searchPup">
          <view class="pheader">
            <text class="title">搜索</text>
            <text class="btn ok" @tap="SubmitSarchDialog()">确 认</text>
            <text class="btn del" @tap="CloseSarchDialog()">取 消</text>
          </view>
          <view class="content">
            <view class="searchbox">
              <text>账户</text>
              <picker
                @change="pickerAccountTypeChange"
                mode="selector"
                :range="accountTypeNames"
                range-key="AccountTypeName"
              >
                <text class="account">{{ curAccountTypeName.AccountTypeName }}</text></picker
              >
            </view>
            <view class="searchbox">
              <text>交易人</text>
              <input class="uni-input" v-model="form.UserName" />
            </view>
            <view class="searchbox">
              <text>年</text>
              <input class="uni-input" v-model="form.DealYear" />
            </view>
            <view class="searchbox">
              <text>月</text>
              <input class="uni-input" v-model="form.DealMonth" />
            </view>
            <view class="searchbox">
              <text>日</text>
              <input class="uni-input" v-model="form.DealDay" />
            </view>
            <view class="searchbox">
              <text>商品类型</text>
              <input class="uni-input" v-model="form.GoodsType" />
            </view>
            <view class="searchbox">
              <text>商品名称</text>
              <input class="uni-input" v-model="form.Goods" />
            </view>
          </view>
        </view>
      </uni-popup>
    </view>
  </scroll-view>
</template>
<style lang="scss">
@import './styles/detail.scss';
</style>
